# -*- coding: UTF-8 -*-

"""

充币通知

监听消息队列 - coin.save

    消息内容 address, memo, coin, amount
    文本存储 逗号分隔

更新 mongodb 中 account 的 余额

"""

import pymongo, redis

# redis
rdb = redis.Redis(host='127.0.0.1', port=6379, db=0, decode_responses=True)

# mongodb
mdb = pymongo.MongoClient(host='127.0.0.1', port=27017, connect=False)

while 1:
    o = rdb.rpop("coin.save")
    if not o:
        time.sleep(0.1)
        continue
    address, memo, coin, amount = o.split(",")
    c = mdb.exchange.coins.find_one({"address": address, "memo": memo, "coin": coin, "type": "save"})
    if not c:
        print("coins is not have", "address:", address, "memo:", memo, "coin:", coin)
        continue
    amount = float(amount)
    mdb.exchange.account.update_one({"userid": c["userid"]}, {"$inc": {"coins." + coin + ".balances": amount}})
